﻿using CommunityToolkit.Mvvm.Input;
using HandyControl.Controls;
using Koala.Pro.Common;
using Koala.Pro.Controls;
using Koala.Pro.Core.Models;
using Koala.Pro.Helpers;
using Koala.Pro.ViewModels;
using System.Windows;
using Wpf.Ui.Controls;

namespace Koala.Pro.Views.Pages
{
    public partial class OuEditPage : System.Windows.Window, INavigableView<OuEditViewModel>
    {
        public OuEditViewModel ViewModel { get; }

        public OuEditPage(OuEditViewModel viewModel)
        {
            ViewModel = viewModel;
            base.DataContext = this;
            InitializeComponent();
        }

        protected override void OnContentRendered(EventArgs e)
        {
            base.OnContentRendered(e);
            ControlHelper.SetDirtyWindow(this);
        }

        [RelayCommand]
        private void Back()
        {
            Close();
        }

        [RelayCommand]
        private async Task Save()
        {
            OuInfo item = ViewModel.Item;
            if (item == null)
            {
                return;
            }
            if (item.Name.IsNullOrWhiteSpace())
            {
                Growl.ErrorGlobal("请输入机构名称");
                txtName.Focus();
                return;
            }
            await ViewModel.Save();
            if (ViewModel.Result.Success)
            {
                Back();
            }
        }

        private void DeptTree_SelectedItemChanged(object sender, RoutedEventArgs e)
        {
            if (e.Source is TreeComboBox { SelectedItem: OuInfo selectedItem })
            {
                ViewModel.Item.PID = selectedItem.Id;
            }
        }
    }
}
